package com.example.simplesvc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.SocketChannel;

public class MyExampleForeverTask implements Runnable{

    private static Logger log = LoggerFactory.getLogger(MyExampleForeverTask.class);
    @Override
    public void run() {


        for(;;) {



            log.info("mock a forever task processing biz");

            //1 sleep，wait，join等操作 可能会引起因为中断引起 InterruptedException
            try {
                Thread.sleep(5000);
            }catch (InterruptedException e) {
                log.info("线程被中断，退出执行");
                return;
            }

            //2 InterruptibleChannel 网络通信操作，可能会引起因为中断引起 ClosedByInterruptException
            try {
                InetSocketAddress addr = new InetSocketAddress("www.163.com",80);
                //建立连接时可如果线程被中断，就会抛出ClosedByInterruptException
                SocketChannel ch = SocketChannel.open(addr);
                ByteBuffer bb = ByteBuffer.allocate(4096);
                //读取数据时可如果线程被中断，就会抛出ClosedByInterruptException
                ch.read(bb);
                bb.flip();
                log.info("received data " + new String( bb.array()));
            }catch (ClosedByInterruptException e) {
                log.info("线程被中断，退出执行");
                return;
            }catch (Exception e) {
                log.error("通信失败", e);
            }



            //3 检查线程状态，若处于中断状态，退出执行
            if(Thread.currentThread().isInterrupted()) {
                log.info("线程被中断，退出执行");
                return;
            }


        }
    }
}
